//index.js
//获取应用实例
import encode from '../../utils/base64.js';
import request from '../../utils/config.js';
let WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
const app = getApp();

Page({
  data: {
    ossImgUrL: 'https://winhc.oss-cn-shanghai.aliyuncs.com/xcx/',
    secret:'f7d98be3828da3b7ab5a2402b9ffcd8e',        
    access_token:'',
    showCardInfo:true,
    showlocation:"none",
    fieldArea:"未填写",
    viewAvatarUrlList:new Array,
    imagesList: new Array(),
    personageData:null,
    showImage: 'none',
    hideImage: 'none',
    opengidName:'',
    showInput: false
  },

  onPullDownRefresh: function () {
    if (!app.globalData.userInfo){
      this.globalTipMsg(this)
    }else{
      this.getLoginInfo(this);
      setTimeout(function(){
        wx.showToast({
          title: '加载成功',
          icon: 'success',
          duration: 1000
        })
        wx.stopPullDownRefresh();
      },1000);
      
    }
    console.log("执行了一次下拉刷新")
  },
  

  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  //点击创建名片
  createCard: function(){
    if (!app.globalData.userInfo) {
      this.globalTipMsg(this)
    } else {
      wx.stopPullDownRefresh();
      wx.navigateTo({
        url: '../createCard/createCard?id=1'
      })
    }
  },

  //查看人气
  seeMoods:()=>{
    wx.navigateTo({
      url: '../moods/moods',
    })
  },

  //查看点赞
  seeZan: ()=>{
    wx.navigateTo({
      url: '../zan/zan',
    })
  },

  //查看留言
  seeLiuyan: ()=>{
    wx.navigateTo({
      url: '../liuyan/liuyan',
    })
  },

  //查看我的人脉
  seeContacts: function(){
    wx.navigateTo({
      url: '../collect/collect',
    })
  },
  toHideImage: function() {
    this.setData({
      showImage: 'none',
      hideImage: 'flex'
    })
  },

  //点击图片预览
  showPic: function(){
    var picUrl = this.data.personageData.avatarUrl;
    wx.previewImage({
      current: picUrl, // 当前显示图片的http链接
      urls: [picUrl] // 需要预览的图片http链接列表
    })
  },

  //编辑卡片
  editCard: function(){
    console.log('app.globalData.openid=' + app.globalData.openid)
    wx.navigateTo({
      // url: '../newEditCard/newEditCard'
      url: '../newEditCard/newEditCard'
      // url:'../otherIndex/otherIndex?openid=oT6r00KaRM70g2QP3ReRa_dlf9wA'
    })
  },

  // 点击显示意见反馈
  giveUsMeg: function() {
    this.setData({
      showInput: true
    })
  },

  // 确定提交意见反馈
  confirmMsg: function() {

  },

  // 取消提交意见反馈
  cancleMsg: function() {
    this.setData({
      showInput: false
    })
  },

  onShow: function(){
    wx.showShareMenu({
      withShareTicket: true
    })
    if (!app.globalData.userInfo){
      // 获取用户信息
      let _that = this;
      wx.getSetting({
        success: res => {
          // if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              app.globalData.userInfo = res.userInfo;
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              // if (this.userInfoReadyCallback) {
              //   this.userInfoReadyCallback(res)
              // }
              wx.showLoading({
                title: '加载中',
              })
              _that.getOpenid(_that);
            },
            fail: res => {
              // var _this = this;
              console.log("获取用户信息失败=", res)
              _that.globalTipMsg(_that);
            }
          })
          // }
        }
      })
    }else{
      if (!app.globalData.persionalInfo) {
        this.setData({
          showCardInfo: true
        });
        wx.hideShareMenu();
      } else {
        wx.showShareMenu({
          withShareTicket: true
        })
        this.getLoginInfo(this);
      }
    }
  },

  //显示没有授权的友好提示框
  globalTipMsg: (_that) => {
    wx.showModal({
      title: '小程序需要你的允许才能正常使用',
      content: '请点击"去设置"并启用"用户信息",然后确定即可正常使用',
      confirmText: '去设置',
      confirmColor: '#35ca14',
      success: function (res) {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              res.authSetting = {
                "scope.userInfo": true
                // "scope.userLocation": true
              }
              console.log("授权设置成功", app.globalData.userInfo)
              //这里是授权成功之后 填写你重新获取数据的js
              _that.getUserinfo(_that);
            }
          })
        } else if (res.cancel) {
          wx.showModal({
            title: '微信登录失败',
            content: '请重新打开小程序，或联系客服解决(错误原因: getUserInfo:fail authdeny)',
            confirmText: '确定',
            confirmColor: '#35ca14',
            success: function (res) {
              if (res.confirm) {
                // 
              } else if (res.cancel) {
                //  
              }
            }
          })
        }
      }
    })
  },

  getUserinfo: (_that) => {
    console.log("再次获取用户信息")
    wx.getUserInfo({
      success: res => {
        console.log("再次获取用户信息拿到的数据值=", res.userInfo)
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.userInfo = res.userInfo;
        _that.getOpenid(_that);
        wx.stopPullDownRefresh();
      }
    })
  },

  //获取openid
  getOpenid: (_that)=>{
    console.log("app.globalData.code:" + app.globalData.code);
    request.request_api(app.globalData.code, (data) => {
          console.log("openid成功", data)
          app.globalData.openid = data.data.openid;
          app.globalData.session_key = data.data.session_key;
          _that.getLoginInfo(_that);
        }, (data) => {
          wx.hideLoading();
          console.log("openid失败", data)
        });
  },

  //获取登录信息
  getLoginInfo: (_that)=>{
    //获取第三方接口登录数据
    let bodyInfo = {
      openid: app.globalData.openid
    };
    request.get_api("login", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("获取信息成功=", res)
      let bodyData = JSON.parse(res.data.body);
      if (res.data.isSuccess == 'T' && bodyData.memUserInfo.mobileNo){
        //保存数据
        app.globalData.persionalInfo = bodyData.memUserInfo;
        var showlocationFlag = 'none';
        if (app.globalData.persionalInfo.address) {
          showlocationFlag = 'block';
        }
        let tempImgList = new Array;
        if (app.globalData.persionalInfo.images) {
          tempImgList = JSON.parse(app.globalData.persionalInfo.images);
          if (tempImgList.length > 0) {
            // console.log("有图", tempImgList)
            _that.setData({
              showImage: 'block',
              hideImage: 'none'
            })
          }
        }
        let advField = "未填写";
        if (app.globalData.persionalInfo.advField) {
          advField = app.globalData.persionalInfo.advField.replace(/,/g, " | ");
        }
        let viewAvatarUrlList = bodyData.avatarUrlList;
        if (viewAvatarUrlList){
          if (viewAvatarUrlList.length > 5){
            viewAvatarUrlList = viewAvatarUrlList.splice(0,5);
          }
        }else{
          viewAvatarUrlList = new Array();
        }
        _that.setData({
          showCardInfo: false,
          personageData: app.globalData.persionalInfo,
          imagesList: tempImgList,
          fieldArea: advField,
          viewAvatarUrlList: viewAvatarUrlList,
          showlocation: showlocationFlag
        });
      }else{
        _that.setData({
          showCardInfo: true
        });
        wx.hideShareMenu();
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取信息失败=", res)
    });
  },
  
  // 拨打电话 
  callPhone: function(){
    var _this = this;
    wx.getSystemInfo({
      success: function (res) {
        // console.log('操作系统版本',res.system) //操作系统版本
        if (res.system.indexOf('iOS') != -1) {
          wx.makePhoneCall({
            phoneNumber: _this.data.personageData.mobileNo //仅为示例，并非真实的电话号码
          })
        } else if (res.system.indexOf('Android') != -1) {
          wx.showModal({
            title: '提示',
            content: '确定呼出电话？',
            success: function (res) {
              if (res.confirm) {
                wx.makePhoneCall({
                  phoneNumber: _this.data.personageData.mobileNo //仅为示例，并非真实的电话号码
                })
              } else if (res.cancel) {

              }
            }
          })
        }
      }
    })
    
  },

  //打开地图
  openMap: function(){
  //   console.log('latitude 纬度', this.data.personageData.latitude * 1);
  //   console.log('longitude 经度', this.data.personageData.longitude * 1)
    wx.openLocation({
      latitude: this.data.personageData.latitude *1,
      longitude: this.data.personageData.longitude *1,
      address: this.data.personageData.address,
      scale: 18
    })
  },

  //显示图片
  showIndexImage: function(e){
    //存储需要的数据
    let tempData = {
      avatarUrl: this.data.personageData.avatarUrl,
      userName: this.data.personageData.userName,
      time: this.data.personageData.openTime,
      images: JSON.parse(this.data.personageData.images)
    }
    wx.setStorageSync('showMoreImgList', tempData);
    var indexKey = e.target.dataset.key;
    wx.navigateTo({
      url: '../photoalbum/photoalbum?key=' + indexKey
    })
  },

  //获取小程序码
  getAppletCode: function(){
    this.getAppletQrCode();
  },

  //获取小程序码access_token
  getAppletQrCode: function(){
    let qrUrl = "pages/otherIndex/otherIndex?openid=" + app.globalData.openid;
    console.log(qrUrl);
    var base64Code = encode.encode(qrUrl);
    app.globalData.qrData = request.request_url+"miniqrQr?path=" + base64Code + "&width=150";
    let transData = {
      name: app.globalData.persionalInfo.userName,
      avatarUrl: app.globalData.persionalInfo.avatarUrl
    }
    wx.navigateTo({
      url: '../appletQr/appletQr?transData=' + JSON.stringify(transData)
    })
  },
  goEditCard: function() {
    wx.navigateTo({
      url: '../newEditCard/newEditCard',
    })
  },

  onLoad: function () {
    wx.showShareMenu({
      withShareTicket: true
    })
    
  },

  //转发
  onShareAppMessage: function(res){
    var picUrl = this.data.personageData.avatarUrl
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log("来自页面内的转发",res.target)
    }
    let This = this;
    return {
      title: '您好，这是我的名片，请惠存',
      path: 'pages/otherIndex/otherIndex?openid=' + app.globalData.openid,
      // imageUrl: picUrl,
      success: function (res) {
        // 转发成功
        console.log("转发成功返回数据=", res)
        wx.showShareMenu({
          // 要求小程序返回分享目标信息
          withShareTicket: true
        });

        if (res.shareTickets) {
          // 获取转发详细信息
          wx.getShareInfo({
            shareTicket: res.shareTickets[0],
            success(res) {
              // res.errMsg; // 错误信息
              // res.encryptedData;  //  解密后为一个 JSON 结构（openGId    群对当前小程序的唯一 ID）
              // res.iv; // 加密算法的初始向量
              let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
              let decodeData = pc.decryptData(res.encryptedData, res.iv);
              console.log('解密后 decodeData: ', decodeData);
              This.setData({
                opengidName: decodeData.openGId
              });
            },
            fail() { },
            complete() { }
          });
        }
      },
      fail: function (res) {
        // 转发失败
      },
      complete: function(){

      }
    }
  }
})
